<?php
class MultiLangFields extends CWidget
{
    protected $model;
    protected $settings=array(
        'model'=>false,
        'class'=>'',
        'name'=>'name',
        'divClass'=>'',
        'inputClass'=>'',
        'inputName'=>'',
        'inputType'=>'text',
        'currentLang'=>'',
        'languages'=>array(),
        'inputIsArray'=>false,
        'inputValue'=>'',
    );

    public function run()
    {
        if(!$this->settings['model']){
            Yii::app()->notification->error=Yii::t('error','modelIsEmpty',array('{widget}'=>'MultiLangFields'));
            return false;
        }

        $this->render('multiLangFields', $this->settings);
    }

    public function setSettings($settings)
    {
        foreach($settings as $name=>$value){
            if(isset($this->settings[$name])) $this->settings[$name]=$value;
        }

        if(!$this->settings['model']){
            $modelClassName=ucfirst($this->settings['class']);
            $this->settings['model']=new $modelClassName();
        }else{
            $modelClassName=get_class($this->settings['model']);
        }

        if(!$this->settings['inputName']) $this->settings['inputName']=$modelClassName.'['.$this->settings['name'].']';

        $this->settings['currentLang']=Yii::app()->language;
        $this->settings['languages']=Language::model()->all;
    }

    public function getValue($code)
    {
        $value=$this->settings['inputValue'] ? $this->settings['inputValue'] : $this->settings['model']->translate($this->settings['name'],$code);
        if(is_array($this->settings['inputValue'])) $value=$this->settings['inputValue'][$code];

        if(!$value && $this->settings['model']->id){
            $result='';
            $name=$this->settings['name'];

            for($i=0; $i<strlen($name); $i++){
                if(ctype_upper($name[$i])){
                    $result.='_'.strtolower($name[$i]);
                }else{
                    $result.=$name[$i];
                }
            }

            $str=$this->settings['model']->translate($result,$code);
            if(!$str) $str=$this->settings['model']->translate($this->settings['model']->tableName().ucfirst($name),$code);

            if(!$str){
                if(isset($this->settings['model']->$result) && $this->settings['model']->$result) $value=$this->settings['model']->$result;
            }else{
                $value=$str;
            }

            if(!$value){
                $method='get'.ucfirst($name);
                if(method_exists($this->settings['model'],$method)) $value=$this->settings['model']->$method($code);
            }
        }

        return $value;
    }
}